/**
 * Created by Administrator on 2017/6/10.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var paymentDao = module.exports;
var CONFIG = require('../config.js');
var taokeCooperate = require('../db/taoke_cooperate.json');
var globalVar = require('../global_var');
var userAgentDao = require('../dao/user_agent');
require('../util/common');
var UserFreezeMoneyDao = require('../dao/user_freeze_money');
var UserMoneyDao = require('../dao/user_money');
var PostHelper = require('../util/postHelper');
var request = require('request');
var vipDao = require('./vip');

function vipType(data, d, cb) {
    switch (parseInt(d[0].vip_type)) {
        case 0 :
            paymentDao.hasRecommender(data.uid,d[0].app_sid, function(err, hasRecommend){
                if(err) {
                    cb('获取推荐人信息失败！');
                }
                var discounts = getDiscountAndMultiRate(hasRecommend, data.num, d[0].discount, d[0].multi_rate);
                var costInfo = {};
                costInfo.hasRecommend = hasRecommend;
                costInfo.total = parseFloat(d[0].price) * parseFloat(discounts.discount) * data.num * parseFloat(discounts.multi_rate); // 应付价格
                costInfo.total = costInfo.total.toFixed(2);
                costInfo.price = parseFloat(d[0].price) * data.num;   //原价
                var vipInfo = {};
                vipInfo.app_sid = d[0].app_sid;
                vipInfo.uid = data.uid;
                vipInfo.vip_sid = d[0].vip_sid;
                paymentDao.getUserVipInfo(vipInfo, function(e, userInfo){
                    if(e) {
                        cb('获取用户vip信息错误');
                    } else {
                        if (userInfo && userInfo.vip_sid && userInfo.vip_sid == vipInfo.vip_sid && userInfo.vip_sid == 'xqkPVip') {
                            cb('抱歉，该会员暂时不支持多次购买哦～！');
                            return;
                        }
                        if (vipInfo.vip_sid == 'xqkPVip') {
                            cb('抱歉，该会员已下架～！');
                            return;
                        }
                        if(userInfo) costInfo.name = userInfo.name ? userInfo.name : undefined;
                        if(!userInfo || userInfo.day <= 0 || userInfo.day == undefined) {
                            costInfo.switchDay = 0;
                            costInfo.avaiDay = parseInt(d[0].duration) * data.num;
                            var now = new Date();
                            now.setDate(now.getDate() + parseInt(costInfo.avaiDay));
                            var day = new Date(now);
                            costInfo.expireDate = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate();
                            cb(null, costInfo);
                        } else {
                            costInfo.switchDay = userInfo.lvl > 0 ?
                                parseInt(parseInt( userInfo.lvl) * parseInt(userInfo.day) / parseInt(d[0].lvl)) : parseInt(userInfo.day);
                            costInfo.avaiDay = costInfo.switchDay + parseInt(d[0].duration) * data.num;
                            var now = new Date();
                            now.setDate(now.getDate() + parseInt(costInfo.avaiDay));
                            var day = new Date(now);
                            costInfo.expireDate = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate();
                            cb(null, costInfo);
                        }
                    }
                });
            });
            break;

        case 1 :
            paymentDao.hasRecommender(data.uid,d[0].app_sid, function(err, hasRecommend){
                if(err) {
                    cb('获取推荐人信息失败！');
                }
                var discounts = getDiscountAndMultiRate(hasRecommend, data.num, d[0].discount, d[0].multi_rate);
                var costInfo = {};
                costInfo.hasRecommend = hasRecommend;
                costInfo.total = parseFloat(d[0].price) * parseFloat(discounts.discount) * data.num * parseFloat(discounts.multi_rate); // 应付价格
                costInfo.total = costInfo.total.toFixed(2);
                costInfo.price = parseFloat(d[0].price) * data.num;   //原价
                var vipInfo = {};
                vipInfo.app_sid = d[0].app_sid;
                vipInfo.uid = data.uid;
                vipInfo.vip_sid = d[0].vip_sid;
                paymentDao.getUserVipInfo(vipInfo, function(e, userInfo){
                    if(e) {
                        cb('获取用户vip信息错误');
                    } else {
                        if(userInfo) costInfo.name = userInfo.name ? userInfo.name : undefined;
                        costInfo.switchScore = (!userInfo) ? 0 :userInfo.lvl;
                        costInfo.avaiScore = parseFloat(costInfo.switchScore) + parseFloat(d[0].lvl);
                        cb(null, costInfo);
                    }
                });
            });
            break;

        case 2 :
            var costInfo = {};
            costInfo.total = d[0].price;
            cb(null, costInfo);
            break;
    }
}

function getOrderCode(app_sid, uid) {
    var now = new Date();
    var code ='' + uid + now.getFullYear() + parseInt(now.getMonth() + 1) + now.getDate() + now.getHours() + now.getMinutes() + Math.floor(Math.random()*10) + Math.floor(Math.random()*10) + now.getSeconds();
    switch (app_sid) {
        case 'benliu' : return code + '1024'; break;
        case 'huoma'  : return code + '2048'; break;
        case 'paodan' : return code + '3072'; break;
        case 'usuz'   : return code + '4096'; break;
        default: return code + '0180';
    }
}

function getDiscountAndMultiRate(hasRecommend, num, discount, rate) {
    var d = {};
    d.discount = hasRecommend ? discount : 1;
    d.multi_rate = (num > 1) ? rate : 1;
    return d;
}

function verifyOrderInfo(data, result, costInfo, cb) {
    switch (parseInt(result[0].vip_type)){
        case 0 :
            var orderInfo = {};
            orderInfo.switchDay = costInfo.switchDay;
            orderInfo.avaiDay = costInfo.avaiDay;
            orderInfo.vip_expire = costInfo.expireDate;
            orderInfo.pay_amount = parseFloat(costInfo.total);
            orderInfo.price = costInfo.price;
            orderInfo.comment = costInfo.comment ? costInfo.comment : null;
            if(orderInfo.pay_amount == parseFloat(parseFloat(data.total).toFixed(2)) && orderInfo.vip_expire == data.expireDate && parseInt(orderInfo.avaiDay) == parseInt(data.avaiDay)){
                orderInfo.uid = data.uid;
                orderInfo.item_id = data.id;
                orderInfo.app_sid = result[0].app_sid;
                orderInfo.vip_sid = result[0].vip_sid;
                orderInfo.vip_lvl = result[0].lvl;
                orderInfo.num = data.num;
                orderInfo.vip_name = result[0].name;
                orderInfo.vip_duration = orderInfo.avaiDay + ' DAY ';
                orderInfo.discount = result[0].discount;
                orderInfo.score = orderInfo.pay_amount;
                orderInfo.status = 12;
                orderInfo.vip_type = result[0].vip_type;
                orderInfo.order_code = getOrderCode(result[0].app_sid, data.uid);
                if(!orderInfo.order_code) {
                    cb('订单信息不正确,请重新下订单1');
                }

                var arr = {};
                arr.uid = data.uid;
                arr.app_sid = result[0].app_sid;
                paymentDao.getRecommenders(arr, function(e, d){
                    if(e) {
                        cb(e);
                        return;
                    } else {
                        orderInfo.commission1 = parseFloat(d.r1_rate1) * orderInfo.pay_amount;
                        orderInfo.commission2 = parseFloat(d.r2_rate2) * orderInfo.pay_amount;
                        orderInfo.vip_expire = new Date(parseInt(new Date().getTime() + parseInt(orderInfo.avaiDay) * 24 * 3600));
                        delete orderInfo.switchDay;
                        delete orderInfo.avaiDay;

                        DBFactory.poolQuery(' insert into order_list set ? ', orderInfo,
                            function () {
                                cb('no connection');
                            },
                            function (e) {
                                if(e) {
                                    console.log(e);
                                    cb('订单生成失败！');
                                    return;
                                } else {
                                    orderInfo.hasRecommend = costInfo.hasRecommend;
                                    cb(null, orderInfo);
                                }
                            });
                    }
                });

            } else {
                cb('订单信息不正确,请重新下订单');
            }
            break;

        case 1 :
            var orderInfo = {};
            orderInfo.switchScore = costInfo.switchScore;
            orderInfo.avaiScore = costInfo.avaiScore;
            orderInfo.vip_expire = 0;
            orderInfo.pay_amount = parseFloat(costInfo.total);
            orderInfo.price = costInfo.price;
            orderInfo.comment = costInfo.comment ? costInfo.comment : null;
            if(data.id == '18') orderInfo.avaiScore = 15000;
            if(orderInfo.pay_amount == parseFloat(data.total) && parseInt(orderInfo.avaiScore) == parseInt(data.avaiScore)){
                orderInfo.uid = data.uid;
                orderInfo.item_id = data.id;
                orderInfo.app_sid = result[0].app_sid;
                orderInfo.vip_sid = result[0].vip_sid;
                orderInfo.vip_lvl = result[0].lvl;
                orderInfo.num = data.num;
                orderInfo.vip_name = result[0].name;
                orderInfo.vip_duration = 0;
                orderInfo.discount = result[0].discount;
                orderInfo.score = orderInfo.pay_amount;
                orderInfo.status = 12;
                orderInfo.vip_type = result[0].vip_type;
                orderInfo.order_code = getOrderCode(result[0].app_sid, data.uid);

                var arr = {};
                arr.uid = data.uid;
                arr.app_sid = result[0].app_sid;

                paymentDao.getRecommenders(arr, function(e, d){
                    if(e) {
                        cb(e);
                        return;
                    } else {
                        orderInfo.commission1 = parseFloat(d.r1_rate1) * orderInfo.pay_amount;
                        orderInfo.commission2 = parseFloat(d.r2_rate2) * orderInfo.pay_amount;

                        delete orderInfo.switchScore;
                        delete orderInfo.avaiScore;

                        DBFactory.poolQuery(' insert into order_list set ? ', orderInfo,
                            function () {
                                cb('no connection');
                            },
                            function (e) {
                                if(e) {
                                    console.log(e);
                                    cb('订单生成失败！');
                                    return;
                                } else {
                                    orderInfo.hasRecommend = costInfo.hasRecommend;
                                    cb(null, orderInfo);
                                }
                            });
                    }
                });
            } else {
                cb('订单信息不正确,请重新下订单');
            }
            break;

        case 2 :
            var orderInfo = {};
            orderInfo.vip_expire = 0;
            orderInfo.pay_amount = parseFloat(costInfo.total);
            orderInfo.price = costInfo.total;
            orderInfo.comment = costInfo.comment ? costInfo.comment : null;
            if(orderInfo.pay_amount == parseFloat(data.total)){
                orderInfo.uid = data.uid;
                orderInfo.item_id = data.id;
                orderInfo.app_sid = result[0].app_sid;
                orderInfo.vip_sid = result[0].vip_sid;
                orderInfo.vip_lvl = result[0].lvl;
                orderInfo.num = data.num;
                orderInfo.vip_name = result[0].name;
                orderInfo.vip_duration = 0;
                orderInfo.discount = result[0].discount;
                orderInfo.score = 0;
                orderInfo.status = 12;
                orderInfo.vip_type = result[0].vip_type;
                orderInfo.order_code = getOrderCode(result[0].app_sid, data.uid);
                orderInfo.commission1 = 0;
                orderInfo.commission2 = 0;
                DBFactory.poolQuery(' insert into order_list set ? ', orderInfo,
                    function () {
                        cb('no connection');
                    },
                    function (e) {
                        if(e) {
                            console.log(e);
                            cb('订单生成失败！');
                            return;
                        } else {
                            cb(null, orderInfo);
                        }
                    });

            } else {
                cb('订单信息不正确,请重新下订单');
            }
            break;

        default: cb('订单信息不正确,请重新下订单');
    }
}

//更改订单状态信息
function updateOrderStatus (data, connection, callback) {
    var sql = 'update order_list set  status = ?, end_time = NOW() , payment = ?, pay_type = ? where order_code = ? ';
    connection.query(sql, [data.status, data.payment, data.pay_type, data.out_trade_no], function(err, result){
        var flag = result  ? true : false;
        callback(err, flag);
    });
}

//获取订单信息
function getOrderDetailInfo(data, connection, callback) {
    var sql = 'select * from order_list where order_code = ?';
    connection.query(sql, [data.out_trade_no], function(err, result){
        var orderInfo = (result && result.length > 0) ? result[0] : undefined;
        if (orderInfo) {orderInfo.left_amount = orderInfo.price;}
        callback(err, orderInfo);
    });
}

//获取订单信息
function getAgentRatio(orderInfo, connection,callback) {
    var sql = 'SELECT account FROM users WHERE uid = ? ';
    connection.query(sql,[orderInfo.uid],function (err,result) {
        if (err) return callback(err);
        if (!result[0] || !result[0].account) return callback('用户不存在');
        orderInfo.account = result[0].account;
        var accounts = [orderInfo.account];
        UserMoneyDao.getRatioByAccounts(orderInfo.app_sid,accounts,1,function (err,result) {
            if(err) return callback(err);
            var resultInfo = result[orderInfo.account] ? result[orderInfo.account] : null;
            var agentRatio = resultInfo.taoCommissionRatio ? resultInfo.taoCommissionRatio : CONFIG.NEW_TAOCOMMISSION_RATIO[1];
            orderInfo.agentRatio = agentRatio;
            if (orderInfo.vip_sid == 'firstVip') orderInfo.agentRatio = CONFIG.NEW_TAOCOMMISSION_RATIO[2];
            callback(null,orderInfo);
        });
    });
}

//更改用户积分和等级
function updateUserScoreAndLvl(orderInfo,connection, callback) {
    var sql = 'update user_app_new_agent as ug inner join ' +
        ' (select g.lvl as lvl from user_app_new_agent as ug LEFT JOIN ' +
        ' app_agent as g on ug.app_sid = g.app_sid where  ug.app_sid = ? ' +
        ' and ug.uid= ?  and ug.score +?>= g.score ORDER BY g.score  desc limit 1) ' +
        ' as lvl set ug.agent_lvl = lvl.lvl, ug.score = ug.score +? where uid =? and app_sid =?';
    connection.query(sql, [orderInfo.app_sid, orderInfo.uid, orderInfo.score, orderInfo.score, orderInfo.uid, orderInfo.app_sid],
        function(err, result){
            orderInfo = result ? orderInfo : undefined;
            callback(err, orderInfo);
        });
}

//获取 一级、二级推荐人（省级代理、市级代理  目前仅usuz）
function getAssociatedPerson(orderInfo,exInfo,connection, callback) {
    var sql = 'select account, recommender, recommender2, client_manager, ' +
        ' agent_1, agent_2, agent_3, agent_4, agent_5, agent_6 from user_app_new_agent where uid = ? and app_sid = ?';
    connection.query(sql, [orderInfo.uid, orderInfo.app_sid], function(err, result){
        var data = (result && result.length > 0) ? result[0] : undefined;
        if(data) {
            if(data.recommender) {
                orderInfo.r1 = data.recommender;
                exInfo.r1 = data.recommender;
            }
            if(data.recommender2) {
                orderInfo.r2 = data.recommender2;
                exInfo.r2 = data.recommender2;
            }
            if(data.client_manager) orderInfo.client_manager = data.client_manager;
            ['agent_1', 'agent_2', 'agent_3', 'agent_4', 'agent_5', 'agent_6', ].forEach(
                function (t) {if(data[t]) orderInfo[t] = data[t];}
            );
            if(data.agent_2) {
                addTaokeInfo(orderInfo);
            }
            if(data.account) {
                orderInfo.account = data.account;
                exInfo.account = data.account;
            }
        }
        orderInfo.buyElite = (orderInfo.vip_sid == 'firstVip') ? true : false;
        callback(err, orderInfo);
    });
}

//获取关联人的uid, money, usuz激活多获取dw_ea,idw_ea,微淘客购买精英的时候多获取djw_ea,idjw_ea (r1,r2 ...)
function getPersonInfo(str, acc, orderInfo, exInfo, connection, callback) {
    var sql = 'select uaa.uid, uaa.money, uaa.pre_agent_lvl ';
    if (orderInfo.vip_sid == 'jihuo' && orderInfo.app_sid == 'usuz') sql += ', uae.dw_ea,uae.idw_ea ';
    if (orderInfo.vip_sid == 'firstVip' && orderInfo.app_sid == 'usuz') sql += ' ,uae.djw_ea,uae.idjw_ea ';
    sql += ' from user_app_new_agent uaa left join user_app_exinfo' +
        ' uae on uaa.uid = uae.uid and uae.app_sid = ? where uaa.account = ? and uaa.app_sid = ?';
    connection.query(sql, [orderInfo.app_sid,acc,orderInfo.app_sid], function(err, result){
        var data = (result && result.length > 0) ? result[0] : undefined;
        if (!data) return callback(err, orderInfo);

        if (data.uid) orderInfo[str + '_uid'] = data.uid;
        if (data.money) orderInfo[str + '_money'] = data.money;
        if (data.pre_agent_lvl) orderInfo[str + '_pre_agent_lvl'] = data.pre_agent_lvl;
        if (orderInfo.app_sid == 'usuz') addVipInfoToOrderInfo(orderInfo,str,data,exInfo);

        callback(err, orderInfo);
    });
}

//拿推荐人的会员信息，并记录,后续添加信息时用到
//拿推荐人的会员信息，并记录,后续添加信息时用到
function addVipInfoToOrderInfo(orderInfo,str,data,exInfo) {

    if (str != 'r1' && str != 'r2') return;
    if (!orderInfo[str + '_uid']) return;
    if (orderInfo.vip_sid != 'jihuo' && orderInfo.vip_sid != 'firstVip') return;
    var isWTK = orderInfo.vip_sid == 'jihuo';
    var r1_key = isWTK ? 'dw_ea' : 'djw_ea'; //直接推荐数的字段名 可能是微淘客或精英微淘客
    var r2_key = isWTK ? 'idw_ea' : 'idjw_ea'; //间接推荐数的字段名 可能是微淘客或精英微淘客
    var total_key = isWTK ? '_wtk_ea' : '_jwtk_ea';  //总推荐数的字段名

    var wtk_r1 = isWTK ? 'no_dw_of_r1' : 'no_djw_of_r1'; //是推荐人该级第几个微淘客或精英
    var total_wtk_r1 = isWTK ? 'no_w_of_r1' : 'no_jw_of_r1'; //是推荐人总共第几个微淘客或精英
    var wtk_r2 = isWTK ? 'no_idw_of_r2' : 'no_idjw_of_r2';
    var total_wtk_r2 = isWTK ? 'no_w_of_r2' : 'no_jw_of_r2';

    exInfo[str + '_uid'] = orderInfo[str + '_uid'];
    exInfo[str + '_' + r1_key] = data[r1_key] ? data[r1_key] : 0;
    exInfo[str + '_' + r2_key] = data[r2_key] ? data[r2_key] : 0;
    orderInfo[str + total_key] = exInfo[str + '_' + r1_key] + exInfo[str + '_' + r2_key];
    if(isEmptyObj(exInfo.selfExInfo)) exInfo.selfExInfo = {};
    if (str == 'r1') {
        exInfo['r1_key'] = r1_key;
        exInfo.selfExInfo[wtk_r1] = exInfo[str + '_' + r1_key] + 1;
        exInfo.selfExInfo[total_wtk_r1] = orderInfo[str + total_key] + 1;
    }
    if (str == 'r2') {
        exInfo['r2_key'] = r2_key;
        exInfo.selfExInfo[wtk_r2] = exInfo[str + '_' + r2_key] + 1;
        exInfo.selfExInfo[total_wtk_r2] = orderInfo[str + total_key] + 1;
    }



}

//修改金额变动 (r1,r2 ...)
function changeAmount(str, orderInfo, comm, unfreezeSid, connection, callback) {
    if (comm <= 0.01) return callback(null,orderInfo);

    var sql = unfreezeSid ? 'insert into freeze_money_record set ? ' : 'insert into user_money set ? ';
    var arr = {};
    arr.order_id = orderInfo.out_trade_no;
    arr.uid = orderInfo[str + '_uid'];
    arr.money = comm;
    arr.app_sid = orderInfo.app_sid;
    arr.comment = getComment(orderInfo,str);
    if(!unfreezeSid){
        arr.original_money = orderInfo[str + '_money'] ? orderInfo[str + '_money'] : 0;
        arr.type = 18;
    } else {
        arr.unfreeze_sid = unfreezeSid;
    }
    connection.query(sql, arr, function (err, result) {
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}


function getComment (orderInfo,str) {
    var comment;
    var vipName = '';
    if (orderInfo.vip_sid == 'jihuo') vipName = '微淘客';
    if (orderInfo.vip_sid == 'firstVip') vipName = '精英微淘客';
    var userAccount = orderInfo.account >= 11 ? '用户****' + orderInfo.account.substr(orderInfo.account.length - 4, 4) + '升级' + vipName + ',' : '用户升级' + vipName + ',';
    if (orderInfo.remarks) {
        comment = orderInfo.remarks;
    } else {
        comment = str == 'r1' ? userAccount + '一级推荐奖励' : userAccount + '二级推荐奖励';
    }
    return comment;
}

//修改直接推荐人佣金，积分，余额（或者冻结金额）
function addDirectAndScoreAndMoneyOrFreeze(orderInfo, comm, acc,isFreeze, connection, callback) {
    if (comm <= 0.01) return callback(null,orderInfo);
    var sql = 'update user_app_new_agent set money_direct = money_direct + ?, score = score +? ';
    sql += isFreeze ? ' , freeze_money = freeze_money + ? ' : ' , money = money + ? ';
    sql += ' where account = ? and app_sid = ? ';
    connection.query(sql, [comm, comm, comm, acc, orderInfo.app_sid], function(err, result){
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}

//修改间接推荐人佣金，积分，余额（或者冻结金额）
function addIndirectAndScoreAndMoneyOrFreeze(orderInfo, comm, acc,isFreeze, connection, callback) {
    if (comm <= 0.01 || !acc) return callback(null,orderInfo);
    var sql = 'update user_app_new_agent set money_indirect = money_indirect + ?, score = score +? ';
    sql += isFreeze ? ' , freeze_money = freeze_money + ? ' : ' , money = money + ? ';
    sql += ' where account = ? and app_sid = ? ';
    connection.query(sql, [comm, comm, comm, acc, orderInfo.app_sid], function(err, result){
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}

//增加积分和（余额或冻结金额）
function addScoreAndMoneyOrFreeze(orderInfo, com, acc, isFreeze, connection, callback) {
    if (com < 0.01) return callback(null,orderInfo);
    var sql = 'update user_app_new_agent set score = score + ? ';
    sql += isFreeze ? ' ,freeze_money = freeze_money + ? ' : ' ,money = money + ? ';
    sql += ' where account = ? and app_sid = ? ';
    connection.query(sql, [com, com, acc, orderInfo.app_sid], function(err, result){
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}


//获取用户之前的VIP信息
function getUserOriginalVip(orderInfo, connection, callback) {
    var sql = 'select * from user_vip where uid =  ? and app_sid = ? and vip_sid = ? ';
    connection.query(sql, [orderInfo.uid, orderInfo.app_sid, orderInfo.vip_sid], function(err, result) {
        if(result.length > 0) {
            var sql2 = 'select name from app_vip_item where app_sid = ? and vip_sid = ? and lvl = ? ';
            connection.query(sql2, [orderInfo.app_sid, orderInfo.vip_sid, result[0].lvl], function(err, data){
                if(result) {
                    orderInfo.original_vip_name = (data.length > 0 && data[0].name != undefined) ? data[0].name : null;
                    orderInfo.original_vip_expire = (result && result[0].end_time != undefined) ? result[0].end_time : null;
                    orderInfo.original_lvl = result[0].lvl ? result[0].lvl : 0;
                }
                callback(err, orderInfo);
            });
        } else {
            callback(err, orderInfo);
        }
    });
}

//获取用户账号
function getAcc(orderInfo, connection, callback) {
    var sql = 'select account from users where uid = ? ';
    connection.query(sql, [orderInfo.uid], function(err, result) {
        orderInfo.account = (result && result[0]) ? result[0].account : undefined;
        if (!orderInfo.account) {
            callback('无该账号信息');
        } else {
            callback(err, orderInfo);
        }
    });
}

//设置VIP权限 或者  增加 积分
function setVipOrScore(orderInfo, connection, callback) {
    var sql = 'replace into user_vip set ? ';
    var data = {};
    data.uid = orderInfo.uid;
    data.account = orderInfo.account;
    data.app_sid = orderInfo.app_sid;
    data.vip_sid = orderInfo.vip_sid;
    if(orderInfo.vip_type == 0) {
        data.vip_type = orderInfo.vip_type;
        data.lvl = orderInfo.vip_lvl;
        data.end_time = orderInfo.vip_expire;
        if(new Date(data.end_time).getTime() > new Date('2030-08-08').getTime()) data.end_time = '2030-08-08';
    } else {
        orderInfo.original_lvl = orderInfo.original_lvl ? orderInfo.original_lvl : 0;
        data.vip_type = orderInfo.vip_type;
        data.lvl = orderInfo.vip_lvl + parseInt(orderInfo.original_lvl);
        data.end_time = '2030-08-08';
    }
    connection.query(sql, data, function(err, result) {
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}

//设置信用积分
function setCreditLvl(orderInfo, connection, callback) {
    var sql = 'replace into user_vip set ? ';
    var data = {};
    data.uid = orderInfo.uid;
    data.account = orderInfo.account;
    data.app_sid = orderInfo.app_sid;
    data.vip_sid = 'creditLvl';
    data.vip_type = 1;
    data.lvl = 102;
    data.end_time = '2030-08-08';
    connection.query(sql, data, function(err, result) {
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}

//设置上单权限
function setPublishGoods(orderInfo, connection, callback) {
    var sql = 'replace into user_vip set ? ';
    var data = {};
    data.uid = orderInfo.uid;
    data.account = orderInfo.account;
    data.app_sid = orderInfo.app_sid;
    data.vip_sid = 'publishGoods';
    data.vip_type = 0;
    data.lvl = 1;
    var now = new Date('2030-08-08');
    // var now = new Date();
    if(parseInt(orderInfo.price) >= 1000) {
        // now.setYear(now.getFullYear() + 1);
    } else {
        // now.setMonth(now.getMonth() + 1);
        sendUidToPd(data.uid);
    }
    data.end_time = now;
    connection.query(sql, data, function(err, result) {
        var arr = [];
        arr.push(data.account);
        arr.push(orderInfo.app_sid);
        arr.push('moneyPoint');
        arr.push('creditLvl');
        arr.push('publishGoods');
        connection.query('delete from vip_log where client_account = ? and app_sid = ? and (vip_sid = ? or vip_sid =? or vip_sid =?) and sign = 0 ',arr, function(e){
            orderInfo = result ? orderInfo : undefined;
            callback(e, orderInfo);
        })
    });
}

//设置信用积分(log)
function setCreditLvlVipLog(orderInfo, connection, callback) {
    var sql = 'insert into vip_log set ? ';
    var vipInfo = {};
    vipInfo.seller_account = 'myself';
    vipInfo.client_account = orderInfo.account;
    vipInfo.vip_name = orderInfo.vip_name;
    vipInfo.duration = orderInfo.vip_duration;
    vipInfo.cost = orderInfo.pay_amount;
    vipInfo.vip_type = 1;
    vipInfo.comment = '购买' + orderInfo.vip_name;
    vipInfo.vip_expire = '2030-08-08';
    vipInfo.lvl = 102;
    vipInfo.recommender = (orderInfo.r1) ? orderInfo.r1 : null;
    vipInfo.recommender2 = (orderInfo.r2) ? orderInfo.r2 : null;
    vipInfo.original_client = (orderInfo.client_manager) ? orderInfo.client_manager : null;
    vipInfo.original_vip_name = orderInfo.original_vip_name;
    vipInfo.original_vip_expire = (orderInfo.original_vip_expire) ? orderInfo.original_vip_expire : null;
    vipInfo.price = orderInfo.price;
    vipInfo.num = orderInfo.num;
    vipInfo.discount = orderInfo.discount;
    vipInfo.multi_rate = (orderInfo.multi_rate == undefined) ? 1 : orderInfo.multi_rate;
    vipInfo.app_sid = orderInfo.app_sid;
    vipInfo.vip_sid = 'creditLvl';
    vipInfo.original_lvl = 0;
    connection.query(sql, vipInfo, function(err, result) {
        callback(err, orderInfo);
    });
}

//设置上单权限(log)
function setPublishGoodsVipLog(orderInfo, connection, callback) {
    var sql = 'insert into vip_log set ? ';
    var vipInfo = {};
    vipInfo.seller_account = 'myself';
    vipInfo.client_account = orderInfo.account;
    vipInfo.vip_name = orderInfo.vip_name;
    vipInfo.duration = orderInfo.vip_duration;
    vipInfo.cost = orderInfo.pay_amount;
    vipInfo.vip_type = 0;
    vipInfo.comment = '购买' + orderInfo.vip_name;
    var now = new Date();
    if(parseInt(orderInfo.price) >= 1000) {
        now.setYear(now.getFullYear() + 1);
    } else {
        now.setMonth(now.getMonth() + 1);
    }
    vipInfo.vip_expire = now;
    vipInfo.lvl = 1;
    vipInfo.recommender = (orderInfo.r1) ? orderInfo.r1 : null;
    vipInfo.recommender2 = (orderInfo.r2) ? orderInfo.r2 : null;
    vipInfo.original_client = (orderInfo.client_manager) ? orderInfo.client_manager : null;
    vipInfo.original_vip_name = orderInfo.original_vip_name;
    vipInfo.original_vip_expire = (orderInfo.original_vip_expire) ? orderInfo.original_vip_expire : null;
    vipInfo.price = orderInfo.price;
    vipInfo.num = orderInfo.num;
    vipInfo.discount = orderInfo.discount;
    vipInfo.multi_rate = (orderInfo.multi_rate == undefined) ? 1 : orderInfo.multi_rate;
    vipInfo.app_sid = orderInfo.app_sid;
    vipInfo.vip_sid = 'publishGoods';
    vipInfo.original_lvl =  0;
    connection.query(sql, vipInfo, function(err, result) {
        callback(err, orderInfo);
    });
}

//新用户完成认证，一级推荐人奖励5000积分
function integralReward(uid, account, recommender, connection, callback) {
    var sql = 'update user_vip set lvl = lvl + ? where account = ? and app_sid = ? and vip_sid = ? ';
    connection.query(sql, [5000, recommender, 'paodan', 'moneyPoint'], function(err, result) {
        if(err) {
            callback(err);
        } else {
            if(result.affectedRows > 0) {
                var log = {};
                var acc = account.length >= 11 ?  account.substr(0,3) + '****' + account.substr(7,4) : '';
                log.seller_account = 'srv';
                log.client_account = recommender;
                log.vip_name = '邀请认证奖励5000积分';
                log.vip_type = 1;
                log.lvl = 5000;
                log.duration = 0;
                log.cost = 0;
                log.comment = '邀请'+ acc +'认证奖励5000积分';
                log.original_vip_name = '平台奖励积分';
                log.price = 0;
                log.vip_expire = '2030-08-08';
                log.app_sid = 'paodan';
                log.vip_sid = 'moneyPoint';
                log.original_vip_expire = '2030-01-01';
                log.sign = 0;
                log.exInfo = uid;
                connection.query('select lvl from user_vip where account = ? and app_sid = ? and vip_sid = ? ', [recommender, 'paodan', 'moneyPoint'], function(e, r) {
                    if(e) {
                        callback(e);
                    } else {
                        log.original_lvl = r[0].lvl;
                        setRewardLog(log, connection, callback);
                    }
                });
            } else {
                callback(null, true);
            }
        }
    });
}
function setRewardLog(data, connection, callback) {
    var sql = 'insert into vip_log set ? ';
    connection.query(sql, data, function(err, result) {
        if(err) {
            callback(err);
        } else {
            callback(null, true);
        }
    });
}

//记录日志
function setVipLog(orderInfo, connection, callback) {
    var sql = 'insert into vip_log set ? ';
    var vipInfo = {};
    vipInfo.seller_account = 'myself';
    vipInfo.client_account = orderInfo.account;
    vipInfo.vip_name = orderInfo.vip_name;
    vipInfo.duration = orderInfo.vip_duration;
    vipInfo.cost = orderInfo.pay_amount;
    vipInfo.vip_type = orderInfo.vip_type;
    vipInfo.comment = '购买' + orderInfo.vip_name;
    if(orderInfo.vip_type == 0) {
        vipInfo.vip_expire = orderInfo.vip_expire;
        if (vipInfo.vip_expire > '2030-08-08') vipInfo.vip_expire = '2030-08-08';
    } else {
        vipInfo.vip_expire = '2030-08-08';
    }
    vipInfo.lvl = orderInfo.vip_lvl;
    vipInfo.recommender = (orderInfo.r1) ? orderInfo.r1 : null;
    vipInfo.recommender2 = (orderInfo.r2) ? orderInfo.r2 : null;
    vipInfo.original_client = (orderInfo.client_manager) ? orderInfo.client_manager : null;
    vipInfo.original_vip_name = orderInfo.original_vip_name;
    vipInfo.original_vip_expire = (orderInfo.original_vip_expire) ? orderInfo.original_vip_expire : null;
    vipInfo.price = orderInfo.price;
    vipInfo.num = orderInfo.num;
    vipInfo.discount = orderInfo.discount;
    vipInfo.multi_rate = (orderInfo.multi_rate == undefined) ? 1 : orderInfo.multi_rate;
    vipInfo.app_sid = orderInfo.app_sid;
    vipInfo.vip_sid = orderInfo.vip_sid;
    vipInfo.original_lvl = (orderInfo.original_lvl) ? orderInfo.original_lvl : 0;
    connection.query(sql, vipInfo, function(err, result) {
        var r = result ? vipInfo : undefined;
        callback(err, true, r);
    });
}

// //查找推荐人是否为精英微淘客    (现在精英微淘客也走三级分销)
// function isFirstVip(str, orderInfo, connection, callback) {
//     var sql = "select count(*) as count,vip_sid from user_vip where account = ? and app_sid = ? ";
//     connection.query(sql, [orderInfo[str], orderInfo.app_sid], function(err, result){
//         orderInfo[str + '_isElite'] = (result[0].count > 1 || result[0].vip_sid == 'firstVip') ? true : false;
//         orderInfo[str + '_isVip'] = (result[0].count > 0) ? true : false;
//         callback(err, orderInfo);
//     });
// }

//查看是推荐人是否还有lvl
function getFirstLvl(orderInfo, connection, callback) {
    var sql = "select lvl, vip_sid from user_vip where account = ? and vip_sid = ? and app_sid = ? and lvl > ? ";
    connection.query(sql, [orderInfo.r1, 'firstVip', orderInfo.app_sid, 0], function(err, result){
        orderInfo.hasFirstVip = (result && result.length > 0) ? true : false;
        callback(err, orderInfo);
    });
}

//减少精英淘客的lvl
function reduceFirstLvl(orderInfo, connection, callback) {
    var sql = 'update user_vip set lvl = lvl - 1 where account = ? and app_sid = ? and vip_sid = ?';
    connection.query(sql, [orderInfo.r1, orderInfo.app_sid, 'firstVip'], function(err, result){
        orderInfo = result ? orderInfo : undefined;
        callback(err, orderInfo);
    });
}

//查看推荐人是否有vip(usuz)
function canSubCom(str, orderInfo, connection, callback) {
    if(!orderInfo[str]) return callback(null, orderInfo);
    var agentRatio = orderInfo.agentRatio;
    var sql = 'select uv.vip_sid,u.pre_agent_lvl,uv.end_time from user_vip uv ' +
        ' left join user_app_new_agent u on uv.uid = u.uid and uv.app_sid = u.app_sid where uv.account = ? and uv.app_sid = ? ';
    connection.query(sql, [orderInfo[str], orderInfo.app_sid], function(err, result){
        var isElite = false;
        var isAgent = false;
        var isVip = false;
        var isXQKVip = false;
        result.forEach(function (userVipInfo) {
            if (userVipInfo.vip_sid == 'firstVip') isElite = true;
            if (userVipInfo.pre_agent_lvl > 0) isAgent = true;
            if (userVipInfo.vip_sid == 'jihuo') isVip = true;
            if (userVipInfo.vip_sid == 'xqkSVip'){
                var nowTime = new Date().getTime();
                var endTime = new Date(userVipInfo.end_time).getTime();
                if (endTime && endTime > nowTime) isXQKVip = true;
            }
        });
        orderInfo[str + '_isElite'] = isElite;
        orderInfo[str + '_isVip'] = isVip;
        if(str == 'r1') {
            orderInfo.commission1 = CONFIG.calcCommission(orderInfo.price, 'reference1', isElite, agentRatio);
            if (orderInfo.buyElite && !isAgent) orderInfo.commission1 = 0;
            if (orderInfo.vip_sid == 'xqkSVip' && !isXQKVip && !isAgent) orderInfo.commission1 = 0;
        }
        if(str == 'r2') {
            orderInfo.commission2 = CONFIG.calcCommission(orderInfo.price, 'reference2', isElite, agentRatio);
        }
        callback(err, orderInfo);
    });

}



function doTradeSuccess(result, data, cb) {
    var type;
    if(parseInt(result.vip_type) <= 1) {
        type = 0;
    } else {
        type = parseInt(result.vip_type);
    }
    if( ((result.app_sid == 'usuz') || (result.app_sid == 'duoke')) && parseInt(result.vip_type) == 0) {
        type = 3;
    }
    if(result.vip_sid == 'xqkVip' || result.vip_sid == 'xqkPVip' || result.vip_sid == 'adScore')  type = 0;
    if(result.vip_sid == 'jf_shop_score') type = 4;
    var exInfo = {};
    switch (parseInt(type)) {
        case 0 :
            DBFactory.getConnection(function(error, connection) {
                if(error) {
                    cb(error);
                } else {
                    async.waterfall([
                        function (callback) {
                            connection.beginTransaction(function(err) {
                                callback(err);
                            });
                        },

                        //更改订单状态信息
                        function (callback) {
                            updateOrderStatus(data, connection, callback);
                        },

                        //获取订单信息
                        function(flag, callback) {
                            if(flag) {
                                getOrderDetailInfo(data, connection, callback);
                            } else {
                                callback('更改订单状态失败！');
                            }
                        },

                        //更改用户积分和等级
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                updateUserScoreAndLvl(orderInfo,connection, callback);
                            } else {
                                callback('获取订单信息失败！');
                            }
                        },

                        //获取 一级、二级推荐人、（省级代理、市级代理  目前仅usuz）
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                getAssociatedPerson(orderInfo, exInfo, connection, callback);
                            } else {
                                callback('更改用户积分和等级失败！');
                            }
                        },

                        //获取一级推荐人的uid, money
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r1 && parseFloat(orderInfo.commission1) != 0) {
                                    getPersonInfo('r1', orderInfo.r1, orderInfo, exInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //修改直接推荐人的佣金,积分，余额
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r1 && parseFloat(orderInfo.commission1) != 0) {
                                    addDirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission1, orderInfo.r1, false, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级推荐人信息失败！');
                            }
                        },

                        //修改一级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r1_uid) {
                                    changeAmount('r1', orderInfo, orderInfo.commission1, null, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('修改直接推荐人的佣金失败！');
                            }
                        },

                        //获取二级推荐人的uid, money
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r2 && parseFloat(orderInfo.commission2) != 0) {
                                    getPersonInfo('r2', orderInfo.r2, orderInfo, exInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('修改一级推荐人的金额变动失败！');
                            }
                        },

                        //修改间接推荐人的佣金,积分，余额
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r2 && parseFloat(orderInfo.commission2) != 0) {
                                    addIndirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission2, orderInfo.r2, false, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取二级推荐人信息失败！');
                            }
                        },

                        //修改二级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r2_uid) {
                                    changeAmount('r2', orderInfo, orderInfo.commission2, null, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('修改间接推荐人的佣金失败！');
                            }
                        },

                        //获取用户前vip信息
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                getUserOriginalVip(orderInfo, connection, callback);
                            } else {
                                callback('修改间接推荐人的积分失败！');
                            }
                        },

                        //查询用户的account
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.account) {
                                    callback(null, orderInfo);
                                } else {
                                    getAcc(orderInfo, connection, callback);
                                }
                            } else {
                                callback('获取用户前vip信息失败！');
                            }
                        },

                        //更改用户vip表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipOrScore(orderInfo, connection, callback);
                            } else {
                                callback('获取用户账号信息失败！');
                            }
                        },

                        //判断是否为购买paodan新人免认证  creditLvl （moneyPoint[15000],creditLvl[102],publishGoods[一个月]）
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.vip_name.indexOf('99免认证') >= 0) {
                                setCreditLvl(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //判断是否为购买paodan新人免认证  publishGoods
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.vip_name.indexOf('99免认证') >= 0) {
                                setPublishGoods(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //若是新人免认证  得再记录另一个权限记录
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.vip_name.indexOf('99免认证') >= 0) {
                                setCreditLvlVipLog(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //若是新人免认证  得再记录另一个权限记录
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.vip_name.indexOf('99免认证') >= 0) {
                                setPublishGoodsVipLog(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //若是新人免认证，上级可奖励5000积分
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.r1 && orderInfo.vip_name.indexOf('99免认证') >= 0) {
                                integralReward(orderInfo.uid, orderInfo.account, orderInfo.r1, connection, function(err, result) {
                                    if(err) {
                                        callback(err);
                                    } else {
                                        callback(null, orderInfo);
                                    }
                                });
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //若购买积分超过1000元则赠送1年的上单权限
                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.app_sid == 'paodan' && parseInt(orderInfo.price) >= 1000 && orderInfo.vip_sid == 'moneyPoint') {
                                setPublishGoods(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        function(orderInfo, callback) {
                            if(orderInfo && orderInfo.app_sid == 'paodan' && parseInt(orderInfo.price) >= 1000 && orderInfo.vip_sid == 'moneyPoint') {
                                setPublishGoodsVipLog(orderInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //记录vip_log表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipLog(orderInfo, connection, callback);
                                addXQKArticleReward(orderInfo);
                            } else {
                                callback(null, false, '日志记录失败！');
                            }
                        }

                    ],function(DbErr, isSuccess, insertId) {
                        if(DbErr) {
                            connection.rollback(function () {
                                connection.release();
                                cb(DbErr);
                            });
                        } else if(!isSuccess) {
                            connection.rollback( function() {
                                connection.release();
                                cb(insertId);
                            });
                        } else {
                            connection.commit(function (e) {
                                if(e) {
                                    connection.rollback( function() {
                                        connection.release();
                                        cb(e);
                                    });
                                } else {
                                    connection.release();
                                    cb(null, insertId);

                                }
                            });
                        }
                    });
                }
            });
            break;

        case 2 :
            DBFactory.getConnection(function(error, connection){
                if(error) {
                    cb(error);
                } else {
                    async.waterfall([
                        function (callback) {
                            connection.beginTransaction(function(err) {
                                callback(err);
                            });
                        },

                        //更改订单状态信息
                        function (callback) {
                            updateOrderStatus (data, connection, callback);
                        },

                        //获取订单信息
                        function(flag, callback) {
                            if(flag) {
                                getOrderDetailInfo(data, connection, callback);
                            } else {
                                callback('更改订单状态失败！');
                            }
                        },

                        //获取用户前vip信息
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                getUserOriginalVip(orderInfo, connection, callback);
                            } else {
                                callback('获取订单信息失败！');
                            }
                        },

                        //查询用户的account
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.account) {
                                    callback(null, orderInfo);
                                } else {
                                    getAcc(orderInfo, connection, callback);
                                }
                            } else {
                                callback('获取用户前vip信息失败！');
                            }
                        },

                        //更改用户vip表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipOrScore(orderInfo, connection, callback);
                            } else {
                                callback('获取用户账号信息失败！');
                            }
                        },

                        //记录vip_log表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipLog(orderInfo, connection, callback);
                            } else {
                                callback(null, false, '日志记录失败！');
                            }
                        }
                    ],function(DbErr,  isSuccess, insertId) {
                        if(DbErr) {
                            connection.rollback(function () {
                                connection.release();
                                cb(DbErr);
                            });
                        } else if(!isSuccess) {
                            connection.rollback( function() {
                                connection.release();
                                cb(insertId);
                            });
                        } else {
                            connection.commit(function (e) {
                                if(e) {
                                    connection.rollback( function() {
                                        connection.release();
                                        cb(e);
                                    });
                                } else {
                                    connection.release();
                                    cb(null, insertId);
                                }
                            });
                        }
                    });
                }
            });
            break;

        case 3 :
            DBFactory.getConnection(function(error, connection){
                if(error) {
                    cb(error);
                } else {
                    async.waterfall([
                        function (callback) {
                            connection.beginTransaction(function(err) {
                                callback(err);
                            });
                        },

                        //更改订单状态信息
                        function (callback) {
                            updateOrderStatus (data, connection, callback);
                        },

                        //获取订单信息
                        function(flag, callback) {
                            if(flag) {
                                getOrderDetailInfo(data, connection, callback);
                            } else {
                                callback('更改订单状态失败！');
                            }
                        },

                        //获取代理比例
                        function (orderInfo,callback) {
                            getAgentRatio(orderInfo,connection,callback);
                        },

                        //获取 一级、二级推荐人、（省级代理、市级代理  区级代理 目前仅usuz）
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                getAssociatedPerson(orderInfo, exInfo, connection, callback);
                            } else {
                                callback('更改用户积分和等级失败！');
                            }
                        },

                        //购买类型为firstVip的话,不走三级分销 (现在也走三级分销)
                        //查找推荐人是否为精英微淘客
                        function(orderInfo, callback) {
                            exInfo.account = orderInfo.account;
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r1) {
                                    // isFirstVip('r1', orderInfo, connection, callback);
                                    canSubCom('r1', orderInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //是微淘客  获取一级推荐人的uid,money
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r1_isVip) {
                                    getPersonInfo('r1', orderInfo.r1, orderInfo, exInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //修改一级推荐人的积分、佣金，总余额，修改前查看一级推荐人的精英微淘客数，如果
                        function(orderInfo, callback) {
                            if(!orderInfo) return callback('获取一级推荐人信息失败！');
                            if(orderInfo.buyElite && orderInfo.r1_isVip) {
                                // var unfreeze_sid = (orderInfo.r1_pre_agent_lvl || orderInfo.r1_isElite || orderInfo.r1_jwtk_ea <= 5) ? false : 'jwtk_limit';
                                if(orderInfo.r1 == orderInfo.taoke_account) orderInfo.commission1 = Math.ceil(orderInfo.taoke_ratio * orderInfo.commission1);
                                orderInfo.commission1 = Math.ceil(parseFloat(orderInfo.commission1));
                                orderInfo.left_amount -= orderInfo.commission1;
                                addDirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission1, orderInfo.r1, null, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //修改一级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r1_isVip && orderInfo.r1_uid) {
                                    var unfreeze_sid = (orderInfo.r1_pre_agent_lvl || orderInfo.r1_isElite || orderInfo.r1_jwtk_ea <= 5) ? false : 'jwtk_limit';
                                    changeAmount('r1', orderInfo, orderInfo.commission1, null, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('修改一级推荐人的积分失败！');
                            }
                        },

                        //查找二级推荐人是否为精英微淘客
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r2) {
                                    // isFirstVip('r2', orderInfo, connection, callback);
                                    canSubCom('r2', orderInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //是微淘客  获取二级推荐人的uid,money
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r2_isVip) {
                                    getPersonInfo('r2', orderInfo.r2, orderInfo, exInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //修改二级推荐人的佣金,积分,余额
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r2_isVip) {
                                    // var unfreeze_sid = (orderInfo.r2_pre_agent_lvl || orderInfo.r2_isElite || orderInfo.r2_jwtk_ea <= 5) ? false : 'jwtk_limit';
                                    if(orderInfo.r2 == orderInfo.taoke_account) orderInfo.commission2 = Math.ceil(orderInfo.taoke_ratio * orderInfo.commission2);
                                    orderInfo.commission2 = Math.ceil(parseFloat(orderInfo.commission2));
                                    orderInfo.left_amount -= orderInfo.commission2;
                                    addIndirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission2, orderInfo.r2, null, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取二级推荐人信息失败！');
                            }
                        },

                        //修改二级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.buyElite && orderInfo.r2_isVip && orderInfo.r2_uid && orderInfo.agentRatio.reference2) {
                                    // var unfreeze_sid = (orderInfo.r2_pre_agent_lvl || orderInfo.r2_isElite || orderInfo.r2_jwtk_ea <= 5) ? false : 'jwtk_limit';
                                    changeAmount('r2', orderInfo, orderInfo.commission2, null, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('修改二级推荐人的积分失败！');
                            }
                        },

                        //购买类型不为精英淘客    查看推荐人是否有firstVip 且 lvl > 0  暂时只有199类型 添加新购买会员类型得修改
                        //获取一级推荐人的uid, money
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r1 && !orderInfo.buyElite) {
                                    getPersonInfo('r1', orderInfo.r1, orderInfo, exInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo)
                                }
                            } else {
                                callback('获取一级二级推荐人失败！');
                            }
                        },

                        //查找一级推荐人是否有会员（是精英微淘客的佣金比例加上去）   没有会员加入到冻结金额
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r1 && !orderInfo.buyElite) {
                                    canSubCom('r1', orderInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级推荐人信息失败！');
                            }
                        },

                        //修改一级推荐人的佣金  (无firstVip权限的) 但有会员
                        function(orderInfo, callback) {
                            if(!orderInfo) return callback('获取一级推荐人信息失败！');
                            if(orderInfo.r1 && !orderInfo.buyElite) {
                                // var isFreeze = (orderInfo.r1_pre_agent_lvl || orderInfo.r1_isElite || (orderInfo.r1_isVip  && orderInfo.r1_wtk_ea < 100)) ? false : true;
                                if(orderInfo.r1 == orderInfo.taoke_account) orderInfo.commission1 *= orderInfo.taoke_ratio;
                                orderInfo.commission1 = Math.ceil(parseFloat(orderInfo.commission1));
                                orderInfo.left_amount -= orderInfo.commission1;
                                addDirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission1, orderInfo.r1, false, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //修改一级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(!orderInfo) return callback('修改直接推荐人的佣金！');
                            if(orderInfo.r1_uid && !orderInfo.buyElite) {
                                // var unfreezeSid = (orderInfo.r1_pre_agent_lvl || orderInfo.r1_isElite || (orderInfo.r1_isVip && orderInfo.r1_wtk_ea < 100)) ? null :
                                //     (orderInfo.r1_isVip ? 'wtk_limit' : 'wtk');
                                changeAmount('r1', orderInfo, orderInfo.commission1, null, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },


                        //获取二级推荐人的uid, money
                        function(orderInfo, callback) {
                            if(!orderInfo) return callback('获取二级推荐人信息失败！');
                            if(orderInfo.r2 && !orderInfo.buyElite) {
                                getPersonInfo('r2', orderInfo.r2, orderInfo, exInfo, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //查找二级推荐人是否有会员   没有会员加入到冻结金额
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r2 && !orderInfo.buyElite) {
                                    canSubCom('r2', orderInfo, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取一级推荐人信息失败！');
                            }
                        },

                        //修改间接推荐人的佣金
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.r2 && !orderInfo.buyElite) {
                                    // var isFreeze = (orderInfo.r2_pre_agent_lvl || orderInfo.r2_isElite || (orderInfo.r2_isVip && orderInfo.r2_wtk_ea < 100)) ? false : true;
                                    if(orderInfo.r2 == orderInfo.taoke_account) orderInfo.commission2 *= orderInfo.taoke_ratio;
                                    orderInfo.commission2 = Math.ceil(parseFloat(orderInfo.commission2));
                                    orderInfo.left_amount -= orderInfo.commission2;
                                    addIndirectAndScoreAndMoneyOrFreeze(orderInfo, orderInfo.commission2, orderInfo.r2, false, connection, callback);
                                } else {
                                    callback(null, orderInfo);
                                }
                            } else {
                                callback('获取间接推荐人的金额失败！');
                            }
                        },

                        //修改二级推荐人的金额变动
                        function(orderInfo, callback) {
                            if(!orderInfo) return callback('修改间接推荐人金额变动失败！');
                            if(orderInfo.r2_uid && !orderInfo.buyElite) {
                                // var unfreezeSid = (orderInfo.r2_pre_agent_lvl || orderInfo.r2_isElite || (orderInfo.r2_isVip && orderInfo.r2_wtk_ea < 100)) ? null :
                                //     (orderInfo.r2_isVip ? 'wtk_limit' : 'wtk');
                                changeAmount('r2', orderInfo, orderInfo.commission2, null, connection, callback);
                            } else {
                                callback(null, orderInfo);
                            }
                        },

                        //修改代理的佣金、金额变动、积分，余额
                        function (orderInfo, callback) {
                            if (orderInfo.vip_sid == 'xqkSVip') {
                                orderInfo.agentRatio = {
                                    agent_1:0,
                                    agent_2:0.125,
                                    agent_3:0,
                                    agent_4:0.1875,
                                    agent_5:0,
                                    agent_6:0.1875,
                                }
                            }
                            function doAgentByLevelStep1(lvl, cb1) {
                                var agentLvlName = 'agent_' + lvl;
                                getPersonInfo('A' + lvl, orderInfo[agentLvlName], orderInfo, exInfo, connection, cb1);
                            }
                            function doAgentByLevelStep2(lvl, cb2) {
                                var agentLvlName = 'agent_' + lvl;
                                var agentFeeName = 'A' + lvl + '_agent_fee';
                                if(lvl == 1){
                                    orderInfo[agentFeeName] = orderInfo.left_amount;
                                    addScoreAndMoneyOrFreeze(orderInfo, orderInfo[agentFeeName], orderInfo[agentLvlName], false, connection, cb2);
                                    return;
                                } else{
                                    var realRatio = orderInfo.agentRatio[agentLvlName];
                                    orderInfo[agentFeeName] = Math.ceil(realRatio * parseInt(orderInfo.price));
                                }
                                if(orderInfo[agentLvlName] == orderInfo.taoke_account){
                                    var newFeed = Math.ceil(orderInfo.taoke_ratio * orderInfo[agentFeeName]);
                                    orderInfo[agentFeeName] = newFeed;
                                }
                                orderInfo.left_amount -= orderInfo[agentFeeName];
                                addScoreAndMoneyOrFreeze(orderInfo, orderInfo[agentFeeName], orderInfo[agentLvlName], false, connection, cb2);
                            }
                            function doAgentByLevelStep3(lvl, cb3) {
                                if(orderInfo['A' + lvl + '_uid']) {
                                    var agentFeeName = 'A' + lvl + '_agent_fee';
                                    var userAccount = orderInfo.account >= 11 ? '用户****' + orderInfo.account.substr(orderInfo.account.length - 4,4) + '升级,' : '用户升级,';
                                    var remarkName = ['总部', '分公司', '管理组', '服务商', '业务组', '总监'];
                                    orderInfo.remarks = remarkName[lvl-1] + '奖励:' + userAccount;
                                    changeAmount('A' + lvl, orderInfo, orderInfo[agentFeeName], null, connection, cb3);
                                } else {
                                    cb3(null);
                                }
                            }
                            function doAgentByLevelStep123(lvl) {
                                if(lvl < 1){
                                    callback(null, orderInfo);
                                    return;
                                }
                                var agentLvlName = 'agent_' + lvl;
                                if(!orderInfo[agentLvlName]) {
                                    doAgentByLevelStep123(lvl - 1);
                                    return;
                                }
                                doAgentByLevelStep1(lvl,function (err1) {
                                    if(err1){
                                        callback(err1);
                                        return;
                                    }
                                    doAgentByLevelStep2(lvl,function (err2) {
                                        if(err2){
                                            callback(err2);
                                            return;
                                        }
                                        doAgentByLevelStep3(lvl,function (err) {
                                            if(err){
                                                callback(err);
                                                return;
                                            }
                                            doAgentByLevelStep123(lvl - 1);
                                        })
                                    })
                                })
                            }

                            if(!orderInfo) {
                                callback('修改市级代理的金额变动失败！');
                                return;
                            }
                            doAgentByLevelStep123(6);
                        },

                        //获取用户前vip信息
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                getUserOriginalVip(orderInfo, connection, callback);
                            } else {
                                callback('修改间接推荐人的积分失败！');
                            }
                        },

                        //查询用户的account
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.account) {
                                    callback(null, orderInfo);
                                } else {
                                    getAcc(orderInfo, connection, callback);
                                }
                            } else {
                                callback('获取用户前vip信息失败！');
                            }
                        },

                        //更改用户vip表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipOrScore(orderInfo, connection, callback);
                            } else {
                                callback('获取用户账号信息失败！');
                            }
                        },

                        //记录vip_log表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipLog(orderInfo, connection, callback);
                                // 升级为精英的  修改等级
                                if(orderInfo.buyElite) {
                                    userAgentDao.setPreAgentLvl({app_sid: orderInfo.app_sid, uid: orderInfo.uid, pre_agent_lvl: 6}, function(err) {if(err) console.log(err);});
                                }
                                if(result.vip_sid == 'xqkSVip') {
                                    var vipInfo = {};
                                    vipInfo.account = orderInfo.account;
                                    vipInfo.uid = orderInfo.uid;
                                    vipInfo.app_sid = orderInfo.app_sid;
                                    vipInfo.vip_sid = 'jihuo';
                                    vipInfo.vip_type = 0;
                                    vipInfo.lvl = 0;
                                    vipInfo.created_time = new Date();
                                    vipInfo.end_time = '2030-08-08';
                                    vipInfo.vip_name = '向前看天使会员赠送微淘客会员';
                                    vipInfo.comment ='向前看天使会员赠送微淘客会员';
                                    vipInfo.seller_account = 'myself';
                                    vipDao.setCustomVip(vipInfo, function() {});
                                }
                            } else {
                                callback(null, false, '日志记录失败！');
                            }
                        }
                    ],function(DbErr,  isSuccess, insertId) {
                        if(DbErr) {
                            connection.rollback(function () {
                                connection.release();
                                cb(DbErr);
                            });
                        } else if(!isSuccess) {
                            connection.rollback( function() {
                                connection.release();
                                cb(insertId);
                            });
                        } else {
                            connection.commit(function (e) {
                                if(e) {
                                    connection.rollback( function() {
                                        connection.release();
                                        cb(e);
                                    });
                                } else {
                                    connection.release();
                                    cb(null, insertId);
                                    if(result.vip_sid == 'jihuo' || result.vip_sid == 'firstVip') {
                                        unfreezeMoney(result.vip_sid,result.uid,result.app_sid);
                                        recordWTKCount(exInfo,result.uid,result.app_sid);
                                    }
                                    // addGiveWTKCount(result.vip_sid,result.uid,result.app_sid);
                                }
                            });
                        }
                    });
                }
            });
            break;

        case 4 :
            DBFactory.getConnection(function(error, connection) {
                if(error) {
                    cb(error);
                } else {
                    async.waterfall([
                        function (callback) {
                            connection.beginTransaction(function(err) {
                                callback(err);
                            });
                        },

                        //更改订单状态信息
                        function (callback) {
                            updateOrderStatus(data, connection, callback);
                        },

                        //获取订单信息
                        function(flag, callback) {
                            if(flag) {
                                getOrderDetailInfo(data, connection, callback);
                            } else {
                                callback('更改订单状态失败！');
                            }
                        },

                        //查询用户的account
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                if(orderInfo.account) {
                                    callback(null, orderInfo);
                                } else {
                                    getAcc(orderInfo, connection, callback);
                                }
                            } else {
                                callback('获取用户前vip信息失败！');
                            }
                        },

                        //更改用户vip表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipOrScore(orderInfo, connection, callback);
                            } else {
                                callback('获取用户账号信息失败！');
                            }
                        },

                        //记录vip_log表
                        function(orderInfo, callback) {
                            if(orderInfo) {
                                setVipLog(orderInfo, connection, callback);
                            } else {
                                callback(null, false, '日志记录失败！');
                            }
                        }

                    ],function(DbErr, isSuccess, insertId) {
                        if(DbErr) {
                            connection.rollback(function () {
                                connection.release();
                                cb(DbErr);
                            });
                        } else if(!isSuccess) {
                            connection.rollback( function() {
                                connection.release();
                                cb(insertId);
                            });
                        } else {
                            connection.commit(function (e) {
                                if(e) {
                                    connection.rollback( function() {
                                        connection.release();
                                        cb(e);
                                    });
                                } else {
                                    connection.release();
                                    cb(null, insertId);
                                }
                            });
                        }
                    });
                }
            });
            break;
    }
}

function addTaokeInfo(orderInfo){
    for(var key in taokeCooperate){
        if(key == orderInfo.agent_2){
            orderInfo.taoke_account = orderInfo.agent_2;
            orderInfo.taoke_ratio = taokeCooperate[key].product_ratio ? taokeCooperate[key].product_ratio : 1;
            break;
        }
    }
}

//解冻相应的冻结金额
function unfreezeMoney(vip_sid,uid,app_sid) {
    var unfreeze_sid = null;
    if(vip_sid == 'jihuo') unfreeze_sid = 'wtk';
    if(vip_sid == 'firstVip') unfreeze_sid = 'jwtk';
    if(unfreeze_sid) {
        UserFreezeMoneyDao.unfreezeMoney({
            uid:uid,
            app_sid: app_sid,
            unfreeze_sid:unfreeze_sid,
        }, function (err, result) {
            if (err) console.log(err);
        });
    }
}

//增加免费赋予微淘客名额
function addGiveWTKCount(vip_sid,uid,app_sid) {
    if (vip_sid != 'firstVip' || app_sid != 'usuz' || !uid) return;
    var sql = "UPDATE user_app_exinfo SET left_wtk_ea = left_wtk_ea + 100 WHERE uid = ? AND app_sid = 'usuz' "
    DBFactory.poolQuery(sql, [uid],
        function () {
            console.log('add left_wtk_ea ERR');
        },
        function (err, result) {
            if (err) {
                console.log('add left_wtk_ea ERR' + err);
                return;
            }
        }
    );
}

function recordWTKCount(exInfo,uid,app_sid) {
    addRecommenderWTKCount(exInfo.r1_uid,exInfo.r1,exInfo['r1_key'],app_sid,function (err) {
        if (err) return;
        addRecommenderWTKCount(exInfo.r2_uid,exInfo.r2,exInfo['r2_key'],app_sid,function (err) {
            if (err) return;
            addSelfWTKInfo(exInfo,uid,exInfo.account,app_sid);
        });

    });
}

function addRecommenderWTKCount(uid,account,key,app_sid,cb) {
    if (!key) cb('参数有误')
    findHasAppExInfo(uid,app_sid,function (err,isHave) {
        if(err) cb(err);
        var sql = isHave ? 'UPDATE user_app_exInfo SET ' :
            'INSERT INTO user_app_exInfo SET ? ';
        var value = [];
        if (isHave) {
            sql += ' ' + key + ' = ' + key + ' + 1  WHERE uid = ? AND app_sid = ? ';
            value.push(uid,app_sid);
        } else {
            var exInfo = {
                uid:uid,
                app_sid:app_sid,
                account:account,
            }
            exInfo[key] = 1;
            value.push(exInfo);
        }
        DBFactory.poolQuery(sql, value,
            function () {
                cb('no collection');
            },
            function (err, result) {
                if (err) {
                    console.log('记录微淘客数量' + sql + ' ERR' + err);
                    cb(err);
                    return;
                }
                cb(null, result);
            }
        );
    })

}

function addSelfWTKInfo(exInfo,uid,account,app_sid) {

    findHasAppExInfo(uid,app_sid,function (err,isHave) {
        if (err) return;
        var sql =  isHave ? 'UPDATE user_app_exInfo SET ' : 'INSERT INTO user_app_exInfo SET ? ';
        var value = [];

        if (isHave) {
            var sqls = [];
            for(var key in exInfo.selfExInfo) {
                sqls.push(' ' + key + ' = ? ');
                value.push(exInfo.selfExInfo[key]);
            }
            if (value.length <= 0) return;
            sql += sqls.toString();
            sql += ' WHERE uid = ? AND app_sid = ? ';
            value.push(uid,app_sid);
        }else {
            exInfo.selfExInfo.uid = uid;
            exInfo.selfExInfo.app_sid = app_sid;
            exInfo.selfExInfo.account = account;
            value.push(exInfo.selfExInfo);
        }
        DBFactory.poolQuery(sql, value,
            function () {
                cb('no collection');
            },
            function (err, result) {
                if (err) {
                    console.log('记录微淘客数量' + sql + ' ERR' + err);
                    return;
                }
            }
        );

    });
}

function findHasAppExInfo(uid,app_sid,cb) {
    var sql = 'SELECT uid FROM user_app_exInfo WHERE uid = ? AND app_sid = ? ';
    DBFactory.poolQuery(sql, [uid,app_sid],
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log('记录微淘客数量SELECT user_app_exInfo ERR' + err);
                cb(err);
                return;
            }
            var exInfo = (result && result[0]) ? result[0] : false;
            cb(null, exInfo);
        }
    );
}

paymentDao.hasRecommender = function(data,app_sid, cb) {
    var sql = ' select recommender from user_app_new_agent where uid = ? and app_sid = ? ';
    DBFactory.poolQuery(sql, [data,app_sid],
        function (){
            cb('no connection');
        },
        function (e, d){
            if(e) {
                console.log(e);
                cb('获取推荐人信息失败！');
                return;
            } else if(d.length > 0 && d[0].recommender != undefined){
                cb(null, true);
            } else {
                cb(null, false);
            }
        });
}

paymentDao.getOriginalVipName = function(data, cb) {
    var sql = 'select name from app_vip_item where app_sid = ? and lvl = ? and vip_sid = ? ';
    DBFactory.poolQuery(sql, [data.app_sid, data.lvl, data.vip_sid],
        function(){
            cb('no connection');
        },
        function (e, d) {
            if(e) {
                cb(e);
                console.log(e);
                return;
            }
            if(d[0]) {
                var info = d[0].name ? d[0].name : undefined;
                cb(null, info)
            } else {
                cb(null, undefined);
            }
        });
}

paymentDao.getUserVipInfo = function(data, cb) {
    if(!data){
        cb(new Error(500));
        return;
    }
    var sql = 'select *, datediff(end_time, now()) as day from user_vip where uid = ?  and  app_sid = ?  and vip_sid = ? ';
    DBFactory.poolQuery(sql, [data.uid, data.app_sid, data.vip_sid],
        function(){
            cb('no connection');
        },
        function (e, d) {
            if(e) {
                cb(e);
                console.log(e);
                return;
            }
            if(d[0]) {
                var info = d[0];
                if(d[0].app_sid && d[0].vip_sid && d[0].lvl) {
                    var arr = {app_sid: d[0].app_sid, vip_sid: d[0].vip_sid, lvl: d[0].lvl};
                    paymentDao.getOriginalVipName(arr, function(e, name){
                        if(e) {
                            cb(e);
                        }
                        info.name = name ? name : undefined;
                        cb(null, info);
                    });
                } else {
                    cb(null, info);
                }
            } else {
                cb(null, undefined);
            }
        });
}

paymentDao.getRecommenders = function(data, cb) {
    if(!data){
        cb(new Error(500));
        return;
    }
    var sql = ' select recommender , recommender2,agent_lvl from user_app_new_agent where uid =? and app_sid = ?';
    DBFactory.poolQuery(sql, [data.uid, data.app_sid],
        function(){
            cb('no connection');
        },
        function (e, d) {
            if(e) {
                cb(e);
                console.log(e);
                return;
            }
            var info = {};
            if(d.length > 0 && d[0].recommender) info.recommender = d[0].recommender;
            if(d.length > 0 && d[0].recommender2) info.recommender2 = d[0].recommender2;
            info = (d.length == 0) ? {} : info;
            info.app_sid = data.app_sid;

            paymentDao.getRate(info, function(e,d){
                if(e) {
                    cb('获取提成比率失败！');
                } else {
                    cb(null, d);
                }
            });
        });
}

paymentDao.getRate = function(data, cb) {
    if(!data){
        cb(new Error(500));
        return;
    }
    var sql = ' select commission_rate1 , commission_rate2 from user_app_new_agent as ug ' +
        ' LEFT JOIN app_agent as g on ug.app_sid = g.app_sid where ug.account = ? and g.app_sid= ? ' +
        ' and ug.agent_lvl = g.lvl ';
    if(data.recommender) {
        DBFactory.poolQuery(sql, [data.recommender, data.app_sid],
            function(){
                cb('no connection');
            },
            function (e, d) {
                if(e) {
                    cb(e);
                    console.log(e);
                    return;
                }
                var info = {};
                info.r1_rate1 = (d.length > 0 && d[0].commission_rate1) ? d[0].commission_rate1 : 0;
                info.r1_rate2 = (d.length > 0 && d[0].commission_rate2) ? d[0].commission_rate2 : 0;
                if(data.recommender2) {
                    DBFactory.poolQuery(sql, [data.recommender2, data.app_sid],
                        function(){
                            cb('no connection');
                        },
                        function (e, d2){
                            if(e) {
                                cb(e);
                                console.log(e);
                                return;
                            }
                            info.r2_rate1 = (d2.length > 0 && d2[0].commission_rate1) ? d2[0].commission_rate1 : 0;
                            info.r2_rate2 = (d2.length > 0 && d2[0].commission_rate2) ? d2[0].commission_rate2 : 0;
                            cb(null, info);
                        });
                } else {
                    info.r2_rate1 = 0;
                    info.r2_rate2 = 0;
                    cb(null, info);
                }
            });
    } else {
        var info = {};
        info.r1_rate1 = 0;
        info.r1_rate2 = 0;
        info.r2_rate1 = 0;
        info.r2_rate2 = 0;
        cb(null, info);
    }
}

function getCurMoneyPoint(data, cb) {
    var sql = 'select lvl from user_vip where uid =? and app_sid =? and vip_sid = ?';
    DBFactory.poolQuery(sql, [data.uid, data.app_sid, data.vip_sid],
        function(){
            cb('no connection');
        },
        function(e, d) {
            if(e) {
                console.log(e);
                cb('获取当前积分发生错误！');
                return;
            } else {
                console.log(d);
                if(d[0]) {
                    var cur = d[0].lvl;
                } else {
                    var cur = 0;
                }
                cb(null, cur);
            }
        });
}

paymentDao.filter = function (data, cb) {
    var sql = ' select * from app_vip_item where status = 1 ';
    var filterInfo = [];
    if(data.app_sid) {
        filterInfo.push(data.app_sid);
        sql += ' and app_sid = ? ';
    }
    if(data.vip_sid) {
        filterInfo.push(data.vip_sid);
        sql += ' and vip_sid = ? ';
    }
    if(data.vip_sid == 'moneyPoint') {
        sql += ' and id != 18 ';
    }
    if(data.plat != 'jntb') {
        sql += ' and id != 29 and id != 30 ';
    }
    sql +=' order by app_sid';
    DBFactory.poolQuery(sql, filterInfo,
        function(){
            cb('no connection');
        },
        function(e, d) {
            if(e) {
                console.log(e);
                cb('获取可购买项列表失败！');
                return;
            } else {
                if(data.vip_sid == 'moneyPoint') {
                    getCurMoneyPoint(data, function(e, curMoneyPoint){
                        if(e) {
                            cb(e);
                            return;
                        } else {
                            curMoneyPoint = (curMoneyPoint != undefined) ? curMoneyPoint : 0;
                            var arr = {list: d, curMoneyPoint: curMoneyPoint};
                            cb(null, arr)
                        }
                    });
                } else {
                    cb(null, d);
                }
            }
        });
}

paymentDao.costInfo = function(data, cb) {
    var sql = ' select * from app_vip_item where id =? and status =1';
    DBFactory.poolQuery(sql, [data.id],
        function () {
            cb('no connection');
        },
        function (e, d) {
            if(e) {
                console.log(e);
                cb('获取产品费用信息失败！');
                return;
            } else {
                if(d.length > 0) {
                    vipType (data, d, function(e, costInfo){
                        if(e) {
                            cb(e);
                        } else {
                            costInfo.name = d[0].name;
                            costInfo.obtainScore = d[0].lvl;
                            cb(null, costInfo);
                        }
                    });
                } else {
                    cb('暂无该vip类型！');
                }
            }
        });
}

function doDeductMoney(info, connection, callback) {
    var sql = 'update user_app_new_agent set money = ? where app_sid = ? and uid = ? ';
    connection.query(sql, [info.money, info.app_sid, info.uid], function(err, result) {
        if(err) return callback(err);
        console.log(result);
        if(result.affectedRows == 0) return callback('余额信息修改发生错误，请重试！');
        recordUserMoney(info, connection, callback);
    });
}
function recordUserMoney(info, connection, callback) {
    var arr = {};
    arr.uid = info.uid;
    arr.app_sid = info.app_sid;
    arr.original_money = info.original_money;
    arr.money = info.c_money;
    arr.comment =  info.vip_name;
    arr.sign = info.sign;
    var sql = 'insert into user_money set ? ';
    connection.query(sql, arr, function(err, result) {
        if(err) return callback(err);
        callback(null, {order_total: info.order_total, um_id: result.insertId});
    });
}
function getBalanceAndDeductMoney(data, total, connection, cb) {
    console.log(data);
    async.waterfall([

        function (callback) {
            var sql = ' select money from user_app_new_agent where app_sid = ? and uid = ? ';
            connection.query(sql, [data.app_sid, data.uid], function(err, result) {
                if(err) {
                    console.log(err);
                    cb('获取抵用金额失败，请重试！');
                } else {
                    var money = (result && result[0] && result[0].money) ? parseFloat(result[0].money) : 0;
                    callback(null, money);
                }

            });
        },

        function(money, callback) {
            if(money == 0 ) return callback(null, {order_total: total});
            var info = {};
            info.uid = data.uid;
            info.app_sid = data.app_sid;
            info.vip_name = data.vip_name ;
            if(money > total) {
                info.money = money - total;
                info.order_total = 0;
                info.c_money = total;
            } else {
                info.money = 0;
                info.order_total = total - money;
                info.c_money = money;
            }
            info.original_money = money;
            info.sign = 1;
            doDeductMoney(info, connection, callback);
        }

    ], cb);
}

paymentDao.createOrder = function(data, cb) {
    if(!data)  return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                var sql = 'select * from app_vip_item where id =? and status =1 ';
                connection.query(sql, [data.id], function(err, result) {
                    if(err){
                        callback(err);
                        console.log(err);
                        return;
                    }
                    if(result.length <= 0 ) return cb('生成订单失败！');
                    data.app_sid = result[0].app_sid;
                    data.vip_sid = result[0].vip_sid;
                    data.vip_name = result[0].name;
                    vipType (data, result, function(e, costInfo){
                        if(e) {
                            callback(e);
                        } else {
                            if(parseInt(data.offset) == 1) {
                                data.vip_name += '(余额抵扣)';
                                getBalanceAndDeductMoney(data, parseFloat(costInfo.total), connection, function(e, money) {
                                    if(e) {
                                        callback('获取抵用金额失败,请重试！');
                                    } else {
                                        costInfo.total = parseFloat(parseFloat(money.order_total).toFixed(2));
                                        costInfo.comment = money.um_id;
                                        verifyOrderInfo(data, result, costInfo, function(err, orderInfo) {
                                            if(err) {
                                                callback(err);
                                            } else {
                                                if(costInfo.total == 0) {
                                                    var d = {status: '13', payment: 'balance', pay_type: 'offset', out_trade_no: orderInfo.order_code};
                                                    paymentDao.tradeSuccess(d, function(e) {
                                                        if(e) {
                                                            console.log(e);
                                                            console.log(orderInfo.order_code + '  已付款 ，权限未添加！' );
                                                        }
                                                    })
                                                }
                                                callback(null, orderInfo);
                                            }
                                        });
                                    }
                                })
                            } else {
                                verifyOrderInfo(data, result, costInfo, function(err, orderInfo){
                                    if(err) {
                                        callback(err);
                                    } else {
                                        callback(null, orderInfo);
                                    }
                                });
                            }
                        }
                    });
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}

paymentDao.getOrderInfo = function(data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        var sql = 'select * from order_list where order_code =  ?';
        DBFactory.poolQuery(sql,[data.orderCode],
            function(){
                cb('no connection');
            },
            function(e, d){
                if(e) {
                    console.log(e);
                    cb('获取订单信息失败！');
                    return;
                }
                if(d[0] == undefined) {
                    cb('获取订单信息失败！');
                } else {
                    cb(null, d[0]);
                }
            });
    }
}

paymentDao.tradeSuccess = function (data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        var sql = ' select vip_type, app_sid, vip_sid, uid from order_list where order_code = ? ';
        DBFactory.poolQuery(sql, [data.out_trade_no],
            function () {
                cb('no connection');
            },
            function (e, d) {
                if(e) {
                    console.log(e);
                    cb('获取订单信息失败！');
                    return;
                } else {
                    doTradeSuccess(d[0], data, function(err, result){
                        if(err) {
                            console.log(err);
                            cb(err);
                        } else {
                            cb(null, result);
                        }
                    });
                }
            });
    }
}

paymentDao.getAppsid = function(data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        var sql = ' select app_sid from order_list where order_code = ? ';
        DBFactory.poolQuery(sql, [data.out_trade_no],
            function () {
                cb('no connection');
            },
            function (e, d) {
                if(e) {
                    console.log(e);
                    cb('获取app_sid信息失败！');
                    return;
                } else {
                    if(d.length > 0) {
                        cb(null, d[0]);
                    } else {
                        cb('未找到app_sid信息失败！');
                    }
                }
            });
    }
}

paymentDao.polling = function(data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        var sql = 'select * from order_list where order_code =  ? and uid = ? ';
        DBFactory.poolQuery(sql,[data.orderCode, data.uid],
            function(){
                cb('no connection');
            },
            function(e, d){
                if(e) {
                    console.log(e);
                    cb('轮询时发生错误！');
                    return;
                }
                if(d.length > 0) {
                    cb(null, d[0]);
                }
            });
    }
}

function canTrial(data, cb) {
    var sql = 'select count(*) as count from user_vip where app_sid = ? and uid = ?';
    DBFactory.poolQuery(sql,[data.app_sid, data.uid],
        function(){
            cb('no connection');
        },
        function(e, d){
            if(e) {
                console.log('canTrial err: ' + e);
                cb('查询是否可试用发生错误！');
                return;
            }
            var result = (d[0].count == 0) ? true : false;
            if(result) {
                getTrialVipItem(data, cb)
            } else {
                cb('无试用权限');
            }
        });
}

function getTrialVipItem(data, cb) {
    var sql = 'select sid, type, 1 lvl, set_type from app_vip where type = ? and app_sid = ? and set_type > 0 ';
    DBFactory.poolQuery(sql,[ 0, data.app_sid],
        function(){
            cb('no connection');
        },
        function(e, d){
            if(e) {
                console.log('getTrialVipItem err: ' + e);
                cb('获取可试用权限发生错误！');
                return;
            }
            if(d.length > 0 ) {
                enableTrialVip(data, d, cb);
            } else {
                cb('暂无可试用权限！');
            }
        });
}

function getTrialVipInfo(data, vipInfo) {
    var itemVipInfo = [];
    var now = new Date();
    var trialTime = new Date(parseInt(now.getTime() + 24*60*60*1000));
    var tenYear = new Date('2030-08-08');
    for(var i=0; i<vipInfo.length; i++) {
        var item = [];
        item.push(data.uid);
        item.push(data.account);
        item.push(data.app_sid);
        item.push(vipInfo[i].sid);
        item.push(vipInfo[i].type);
        item.push(vipInfo[i].lvl);
        item.push(now);
        if(parseInt(vipInfo[i].set_type) == 1) {
            item.push(trialTime);
        } else if(parseInt(vipInfo[i].set_type) == 2){
            item.push(tenYear);
        }
        itemVipInfo.push(item);
    }
    return itemVipInfo;
}

function enableTrialVip(data, result, cb) {
    var sql = 'insert into user_vip(`uid`, `account`, `app_sid`, `vip_sid`, `vip_type`, `lvl`, `created_time`, `end_time`) ' +
        ' VALUES ?';
    var itemVipInfo = getTrialVipInfo(data, result);
    DBFactory.poolQuery(sql, [itemVipInfo],
        function(){
            cb('no connection');
        },
        function(e){
            if(e) {
                console.log('enableTrialVip err: ' + e);
                cb('开启试用权限发生错误！');
                return;
            }
            cb(null, 'success');
        });
}

paymentDao.trialOneDay = function(data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        canTrial(data, function(error, result){
            if(error) {
                cb(error);
            } else {
                cb(null, result);
            }
        });
    }
}

paymentDao.shopExchange = function(data, cb) {
    if(!data) return cb(new Error(500));
    DBFactory.getConnection(function(error, connection) {
        if(error) {
            cb(error);
        } else {
            async.waterfall([
                function (callback) {
                    connection.beginTransaction(function(err) {
                        callback(err);
                    });
                },

                //查看用户积分是否够兑换
                function(callback) {
                    var sql = 'select sign_score as score from user_app_exInfo where uid = ? and app_sid = ? ';
                    connection.query(sql, [data.uid, data.app_sid], function(err, result){
                        var canExchange = (parseFloat(result[0].score) > parseFloat(data.sum))  ? true : false;
                        callback(err, canExchange);
                    });
                },

                //积分足够，扣除积分
                function(canExchange, callback) {
                    if(canExchange) {
                        var sql = 'update user_app_exInfo set sign_score = sign_score - ? where uid = ? and app_sid = ? ';
                        connection.query(sql, [data.sum, data.uid, data.app_sid], function(err, result){
                            result = result.affectedRows > 0 ? true : false;
                            callback(err, result);
                        });
                    } else {
                        callback('兑换失败，您的积分不足！');
                    }
                },

                //记录积分变动


                //请求版本号
                // function(result, callback) {
                //     if(result) {
                //         var param = {};
                //         param.app_time = new Date().getTime();
                //         param.app_key = 'shopmall';
                //         param.app_sign = getAppSign(param.app_key,globalVar.apps[param.app_key],param.app_time);
                //         baseRequest(CONFIG.ShopHost, '/order/getVersion', param, function(err, data){
                //             if(err) {
                //                 console.log(err);
                //                 callback('获取版本号错误！');
                //             } else {
                //                 var newVersion = parseInt(data);
                //                 callback(null, newVersion);
                //             }
                //         });
                //     } else {
                //         callback('兑换时发生错误！');
                //     }
                // },


                // function(version, callback) {
                //     if(version > parseInt(data.v)) {
                //         callback('网络繁忙，请重试！');
                //     } else {
                //         //记录
                //     }
                // },


                //完成交易


            ],function(DbErr,  isSuccess, insertId) {
                if(DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if(!isSuccess) {
                    connection.rollback( function() {
                        connection.release();
                        cb(insertId);
                    });
                } else {
                    connection.commit(function (e) {
                        if(e) {
                            connection.rollback( function() {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, insertId);
                        }
                    });
                }
            });
        }
    });
}

function sendUidToPd(uid) {
    var param = {};
    param.app_time = new Date().getTime();
    param.uid = uid;
    param.app_key = 'paodan';
    param.app_sign = getAppSign(param.app_key,globalVar.apps[param.app_key],param.app_time);

    baseRequest('http://' + CONFIG.PDHost, '/affirm/freeAudit2', param, function(err, data){
        // baseRequest('http://10.0.0.125:7000', '/affirm/freeAudit2', param, function(err, data){
        if(err) {
            console.log('sendUidToPd err:' + err);
        }
        console.log(data);
    });
}

function addXQKArticleReward(data) {
    var param = {};
    param.uid = data.uid;
    param.order_code = data.order_code;
    param.pay_amount = data.pay_amount;
    param.app_sid = data.app_sid;
    param.account = data.account;
    baseRequest('http://' + CONFIG.USUZHost, '/reward/add_xqk_article_reward', param, function(err, data){
        if(err) {
            console.log('addXQKArticleReward err:' + err);
        }
        console.log(data);
    });
}

//付款失败（有用余额抵用的， 修改回原来的金额）
function doRecoveryMoney(data, info, connection, callback) {
    var sql = 'select money from user_money where id = ? and uid = ? ';
    connection.query(sql, [info.um_id, data.uid], function(err, result) {
        if(err) return callback(err);
        if(result && result[0] && parseFloat(result[0].money) > 0) {
            var sql = 'select money from user_app_new_agent where uid = ?  and app_sid = ? ';
            connection.query(sql, [data.uid, data.app_sid], function(e, r) {
                if(e) return callback(e);
                var obj = {};
                obj.uid = data.uid;
                obj.app_sid = data.app_sid;
                obj.original_money = r[0].money;
                obj.c_money = result[0].money;
                obj.vip_name = info.vip_name;
                obj.sign = 0;
                var sql = 'update user_app_new_agent set money = money + ? where uid = ? and app_sid = ? ';
                connection.query(sql, [ result[0].money, data.uid, data.app_sid], function(e1, r1) {
                    if(e1) return callback(e1);
                    if(r1.affectedRows > 0) {
                        obj.order_code = data.order_code;
                        recordUserMoneyAndOrderList(obj, connection, callback);
                    } else {
                        callback('恢复金额失败！');
                    }
                });
            });
        } else {
            callback(null, null);
        }
    })
}
function recordUserMoneyAndOrderList(data, connection, callback) {
    recordUserMoney(data, connection, function(err, result) {
        if(err) return callback(err);
        var del_ol_sql = 'delete from order_list where order_code = ? ';
        connection.query(del_ol_sql, [data.order_code], function(e, r) {
            if(e) return callback(e);
            if(r.affectedRows > 0) {
                callback(null, null);
            } else {
                callback('清除订单记录失败！');
            }
        });
    })
}
paymentDao.recoveryMoney = function(data, cb) {
    if(!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                var sql = 'select comment,vip_name from order_list where order_code = ? and status = 12 and uid = ? and app_sid = ? ';
                connection.query(sql, [data.order_code, data.uid, data.app_sid], function(err, result) {
                    if(err) {
                        callback(err);
                    } else {
                        var info = {};
                        info.canRecovery = (result.length > 0  && result[0] && result[0].comment) ? true : false;
                        if(result && result[0] && result[0].comment) {
                            info.um_id = result[0].comment;
                            info.vip_name = result[0].vip_name + '(付款失败，余额返还)';
                        }
                        callback(null, info);
                    }
                });
            },

            function (info, callback) {
                if(info.canRecovery) {
                    doRecoveryMoney(data, info, connection, callback);
                } else {
                    callback(null, null);
                }
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });
}

paymentDao.getTradeOrderInfo = function(data, cb) {
    if(!data) return cb(new Error(500));
    var sql = 'SELECT ol.*,u.account FROM order_list ol LEFT JOIN users u ON ol.uid = u.uid WHERE ol.uid = ? ';
    var value = [data.uid];
    if (data.order_code) {
        sql += ' AND ol.order_code = ? ';
        value.push(data.order_code);
    }
    DBFactory.poolQuery(sql,value,
        function () {
            cb('no connection');
        },
        function (e,result) {
            if(e) {
                console.log(e);
                cb('订单查询失败！');
                return;
            } else {
                if (!result[0].pay_account) result[0].pay_account = '187***@163.com';
                cb(null, result[0]);
            }
        });
}

paymentDao.getPartnerInfo = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select * from partner_info where name = ? ';
    DBFactory.poolQuery(sql, [data],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('getPartnerInfo Err: ' + err);
                return cb(err);
            } else {
                if(result.length == 0 ) return cb('未找到合作者相关信息！');
                cb(null, result[0]);
            }
        }
    );
}

paymentDao.saveCustomOrder = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'insert into partner_order set  ? ';
    DBFactory.poolQuery(sql, data,
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('saveCustomOrder Err: ' + err);
                return cb(err);
            } else {
                cb(null, result.insertId);
            }
        }
    );
}

function addPartnerTotalMoney(data, cb) {
    var sql = 'update partner_info set money = money + ? where id = ? ';
    data.total_amount = (parseFloat(data.total_amount) * CONFIG.SERVICE_PARTNER_RATE).toFixed(2);
    DBFactory.poolQuery(sql, [data.total_amount, data.pi_id],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('addPartnerTotalMoney : ' + data.out_trade_no + ' /支付成功，总资产未添加！');
                console.log('addPartnerTotalMoney Err: ' + err);
                return cb(err);
            }
            if(result.affectedRows) {
                cb(null, null);
            } else {
                console.log('out_trade_no : ' + data.out_trade_no + ' /支付成功，总资产未添加！');
                return cb('支付成功，修改状态失败！');
            }
        }
    );
}
function getSecretByPiId(data, cb) {
    var sql = 'select secret from partner_info where id = ? ';
    DBFactory.poolQuery(sql, [data.pi_id],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('getSecretByPiId Err: ' + err);
                return cb(err);
            }
            if(result.length > 0) {
                cb(null, result[0].secret);
            } else {
                cb('获取secret失败！');
            }
        }
    );
}
function getPartnerOrderInfo(data, cb) {
    var sql = "select * from partner_order where out_trade_no = ? ";
    DBFactory.poolQuery(sql, [data.out_trade_no],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('out_trade_no : ' + data.out_trade_no + ' /支付成功1，回调通知失败！');
                console.log('callbackPartner Err: ' + err);
                return cb(err);
            }
            if(result.length > 0) {
                cb(null, result);
            } else {
                cb('无该订单信息！');
                console.log('out_trade_no : ' + data.out_trade_no + ' /支付成功2，回调通知失败！');
            }
        }
    );
}
function url_encode(url){
    url = encodeURIComponent(url);
    url = url.replace(/\%3A/g, ":");
    url = url.replace(/\%2F/g, "/");
    url = url.replace(/\%3F/g, "?");
    url = url.replace(/\%3D/g, "=");
    url = url.replace(/\%26/g, "&");
    return url;
}
function partnerRequest(url, param, callback) {
    url += '?';
    for(var key in param){
        if(!param[key]) {
            continue;
        }
        url += key + '='  + param[key]  + '&';
    }
    var form = '';
    for(var key in param){
        form += key + '='  + param[key] + '&';
    }
    url = url_encode(url.substr(0,url.length-1));

    var options = {
        url: url,
        method: 'POST',
        form: form
    };
    request(options, function (error, response, body) {
        if (error && response && response.statusCode != 200 && !body) {
            callback('服务器异常，请稍后重试');
            console.log(body);
            console.log(error);
            return;
        } else {
            callback(null, body);
        }
    });
}
function callbackPartner(data, cb, c) {
    var param = data.param;
    param.t = new Date().getTime();
    if(!c) c = 1;
    if(c > 6) return;
    getSecretByPiId(data, function(err, secret) {
        if(err) {
            console.log(err);
            return cb(err);
        } else {
            param.sign = getPartnerSign(secret, param.t);
            partnerRequest(param.url, param, function(e, d) {
                if(e) {
                    console.log('callbackPartner ERR： ');
                    console.log(e);
                } else {
                    if(d == 'SUCCESS' || d == 'success') {
                        cb(null, d);
                    } else {
                        console.log(d);
                        console.log(c);
                        console.log(data.param);
                        console.log('----callbackPartner----err');
                        setTimeout(function(){
                            ++c;
                            callbackPartner(data, cb, c)
                        }, 1000)
                    }
                }
            })
        }
    })
}
function updateShopPartnerOrderStatus(data) {
    if(!data.wx_pay_acc) data.wx_pay_acc = null;
    if(data.buyer_logon_id) data.ali_pay_acc = data.buyer_logon_id;
    var sql = 'update shop_order set status = 3, ali_pay_acc = ?, wx_pay_acc = ?, pay_date = ? ';
    var arr = [data.ali_pay_acc, data.wx_pay_acc, new Date()];
    if(data.buyer_id) {
        sql += ' , buyer_id = ? ';
        arr.push(data.buyer_id);
    }
    sql += ' where order_code = ? ';
    arr.push(data.out_trade_no);
    DBFactory.poolQuery(sql, arr,
        function(){
            console.log('no collection');
        },function (err, result) {
            if(err){
                console.log('updateShopPartnerOrderStatus err: ' + err);
                return;
            } else {
                if(!result.affectedRows) {
                    console.log('updateShopPartnerOrderStatus no affectedRows !');
                }
            }
        }
    );
}
paymentDao.partnerTradeSuccess = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = "update partner_order set status = ?, pay_date = now(), trade_no = ? where out_trade_no = ? ";
    DBFactory.poolQuery(sql, [data.status, data.trade_no, data.out_trade_no],
        function(){
            cb('no collection');
        },function (err, result) {
            if(err){
                console.log('out_trade_no : ' + data.out_trade_no + ' /支付成功，未修改状态！');
                console.log('partnerTradeSuccess Err: ' + err);
                return cb(err);
            }
            if(result.affectedRows) {
                getPartnerOrderInfo(data, function(err, result) {
                    if(err) {
                        console.log(err);
                        return;
                    } else {
                        data.param = result[0];
                        data.pi_id = result[0].pi_id;
                        addPartnerTotalMoney(data, function(){});
                        if(data.pi_id != 2) callbackPartner(data, function(){});
                    }
                });
                cb(null, null);
            } else {
                console.log('out_trade_no : ' + data.out_trade_no + ' /支付成功，未修改状态！');
                return cb('支付成功，修改状态失败！');
            }
        }
    );
}

//积分商城抵用积分购买
paymentDao.createCustomOrder = function(data, cb) {
    if(!data) return cb(new ERR(500));
    DBFactory.poolQuery(' insert into order_list set ? ', data,
        function () {
            cb('no connection');
        },
        function (e) {
            if(e) return cb('订单生成失败！');
            cb(null, data);
        }
    );
}